<?php

namespace App\Models\Admin;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Model;
use App\Common\ValidateHandler;
use App\Models\Admin\Grade;

class TeamAward extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'award_name', 'min_level', 'division_num',
        'radio_inner', 'radio_outer', 'rela_num', 'n_inner',
        'created_at', 'updated_at','bd_award_name','bd_min_level',
        'bd_division_num','bd_radio_inner'
    ];

    const AWARDINI = [
        'award_name' => '富利指数',
        'minLevel' => 0,
        'divisionNum' => 3,
        'nInner' => 100,
        'radioInner' => [
            ['rela' => 1, 'text' => '第一代的比例：', 'radio' => 10],
            ['rela' => 2, 'text' => '第二代的比例：', 'radio' => 5],
            ['rela' => 3, 'text' => '第三代的比例：', 'radio' => 2]
        ],
        'radioOuter' => 4,
        'relaNum' => 25,
        'bd_award_name' => '报单指数',
        'bd_min_level' => 0,
        'bd_division_num' => 2,
        'bd_radio_inner' => [
            ['rela' => 1, 'text' => '第一代的比例：', 'radio' => 10],
            ['rela' => 2, 'text' => '第二代的比例：', 'radio' => 5]
        ]
    ];
    // 获取分享经济信息
    public function getTeamAwardText($id, $grade)
    {
        $team_award = $this->where('store_id', $id)->first();
        $team_award['min_level_cn'] = $team_award['min_level'].' : '.$grade[$team_award['min_level']]['title'];
        $team_award['all_num'] = $team_award['division_num'] + $team_award['rela_num'];
        $n_inner = '订单金额 * '.$team_award['n_inner'].'%';
        $n_outer = '订单金额 * '.($team_award['rela_num']*$team_award['radio_outer']).' %';
        $team_award['all_price'] = '订单金额 * '.($team_award['n_inner']+$team_award['rela_num']*$team_award['radio_outer']).' %';
        $team_award['n_inner_price'] = $n_inner;
        $n_inner_de = json_decode($team_award['radio_inner'], 1);
        $length = count($n_inner_de);
        $team_award['radio_inner_text'] = $this->radioInnerText($n_inner_de, $length); // ##########333333
        $team_award['n_outer_price'] = $n_outer;
        $team_award['radio_outer_text'] = $team_award['radio_outer'].'%';
        return $team_award;
    }
    public function radioInnerText($n_inner_de, $length)
    {
        $str = '';
        for ($i = 1; $i <= $length; $i++) {
            $str .= '第 '.$i.' 代比例 : '.($n_inner_de[$i]*100).'%;  ';
        }
        return $str;
    }
    // [验证]初始化指定店铺 的 团队奖励信息
    public function analyAward($id)
    {
        $Grade = new Grade;
        $validateGrade = $Grade->validateGrade($id);
        if($validateGrade['code'] !== 20000){
            return $validateGrade;
        }else{
            $storeGarde = $validateGrade['data']['data'];
        }
        if (empty($storeGarde)) {
            return $this->error(['info' => '['.$id.']店铺等级信息不存在!请先完善店铺等级信息!']);
        } else {
            return $this->getAward($id);
        }
    }

    // 获取指定店铺的初始化数据
    public function getAward($id)
    {
        $awardInfo = [];
        $award = $this->where('store_id', $id)->first();
        if (empty($award)) {
            $awardInfo = self::AWARDINI;
        } else {
            $awardInfo['awardName'] = $award['award_name'];
            $awardInfo['minLevel'] = $award['min_level'];
            $awardInfo['divisionNum'] = $award['division_num'];
            $awardInfo['nInner'] = $award['n_inner'];
            $awardInfo['radioInner'] = $this->radioInner($award,1);// 解析数据库将数据转变为前台可用格式
            $awardInfo['radioOuter'] = $award['radio_outer'];
            $awardInfo['relaNum'] = $award['rela_num'];

            $awardInfo['bdAwardName'] = $award['bd_award_name'];
            $awardInfo['bdMinLevel'] = $award['bd_min_level'];
            $awardInfo['bdDivisionNum'] = $award['bd_division_num'];
            $awardInfo['bdRadioInner'] = $this->radioInner($award,0);// 解析数据库将数据转变为前台可用格式
        }
        $Grade = new Grade;
        $gradeInfo = $Grade->gradeOptions($id);
        return $this->success(['data' => $awardInfo, 'grade' => $gradeInfo, 'info' => '['.$id.']店铺团队奖励信息初始化成功!']);
    }

    // 根据 N级数目 / N级比例 形成前台所需的格式
    public function radioInner($award,$type)
    {   

        $divisionNum = $type == 1 ? $award['division_num'] : $award['bd_division_num'];
        $radio = $type == 1 ? json_decode($award['radio_inner']) : json_decode($award['bd_radio_inner']);
        $radioInner = [];
        for ($x = 1; $x <= $divisionNum; $x++) {
            // ['rela' => 1, 'text' => '第一代的比例：', 'radio' => 0],
            $radioInner[$x]['rela'] = $x;
            $radioInner[$x]['radio'] = ($radio->$x)*100;
            $radioInner[$x]['text'] = '第 '.$x.' 代的比例：';
        }
        return $radioInner;
    }
    public function insertAnlayArr($id, $data)
    {
        // 验证 店铺 / 店铺等级信息
        $analyAward = $this->analyAward($id, 1);
        if ($analyAward['code'] != 20000) {
            return $analyAward;
        }
        // 验证 并 得到需要插入的数据格式
        $insertAward = $this->foreachGet($data, $id);
        if ($insertAward['code'] != 20000) {
            return $insertAward;
        }
        // 验证团队奖励数据是否存在 , 并以此决定 插入 或 更新
        $awardGold = $this->awardGold($id);
        if ($awardGold) {
            $back = $this->where('store_id', $id)->update($insertAward['data']['data']);
        } else {
            $back = $this->create($insertAward['data']['data']);
        }
        if (!$back) {
            return $this->error(['data' =>  $insertAward['data']['data'],'info' => '['.$id.']店铺团队奖励信息创建失败!']);
        }else{
            return $this->success(['data' =>  $insertAward['data']['data'], 'info' => '['.$id.']店铺团队奖励信息创建成功!']);
        }
    }

    // 遍历前台数据 形成插入的内容
    public function foreachGet($data, $id)
    {
        $insert = [];
        $res = $this->validate($data);
        if (!$res['res']) {
            return $this->error(['info' => $res['info']]);
        }
        $insert['store_id'] = $id;
        $insert['award_name'] = $data['awardName'];
        $insert['min_level'] = $data['minLevel'];
        $insert['division_num'] = $data['divisionNum'];

        $radio = $this->insertRadio($data['radioInner']);
        $insert['radio_inner'] = $radio ? json_encode($radio) : $radio;// 通过前台数据 得到 数据库所需数据
        
        $insert['radio_outer'] = $data['radioOuter'];
        $insert['rela_num'] = $data['relaNum'];
        $insert['n_inner'] = $data['nInner'];

        $insert['bd_award_name'] = $data['bdAwardName'];
        $insert['bd_min_level'] = $data['bdMinLevel'];
        $insert['bd_division_num'] = $data['bdDivisionNum'];

        $bd_radio = $this->insertRadio($data['bdRadioInner']);
        $insert['bd_radio_inner'] = $bd_radio ? json_encode($bd_radio) : $bd_radio;// 通过前台数据 得到 数据库所需数据

        return $this->success(['data' =>  $insert, 'info' => '插入数据验证成功!']);
    }

    //店铺会员等级表 字段合法性验证
    private function validate($data)
    {
        $arr = [
            0 => [
                'name' => '团队奖励名称',
                'value' => $data['awardName'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 10
            ],
            1 => [
                'name' => '最小等级',
                'value' => $data['minLevel'],
                'func' => 'range_num',
                'min' => 0,
                'max' => 99
            ],
            2 => [
                'name' => 'N级数目',
                'value' => $data['divisionNum'],
                'func' => 'range_num',
                'min' => 0,
                'max' => 10
            ],
            3 => [
                'name' => 'N级外比例',
                'value' => $data['radioOuter'],
                'func' => 'range_num',
                'min' => 0,
                'max' => 100
            ],
            4 => [
                'name' => '代数',
                'value' => $data['relaNum'],
                'func' => 'range_num',
                'min' => 0,
                'max' => 100
            ],
            5 => [
                'name' => 'N级内订单倍率',
                'value' => $data['nInner'],
                'func' => 'range_num',
                'min' => 0,
                'max' => 10000
            ],
            6 => [
                'name' => '新报单模式团队奖励名称',
                'value' => $data['bdAwardName'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 10
            ],
            7 => [
                'name' => '新报单模式N级数目',
                'value' => $data['bdDivisionNum'],
                'func' => 'range_num',
                'min' => 0,
                'max' => 10
            ]
            
        ];
        return ValidateHandler::do($arr);
    }
    public function insertRadio($data)
    {
        $radio = [];
        // 遍历 前台数据 , 形成新的对象[ 代数为键 / 比例为值 ]
        if(empty($data)){
            return '';
        }
        foreach ($data as $key => $val) {
            $radio[$val['rela']] = $val['radio']/100;
        }
        return $radio;
    }
    // 验证此店铺团队奖励是否存在
    public function awardGold($id)
    {
        return $this->where('store_id', $id)->first();
    }
}
